package com.crm.aftersale.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.aftersale.domain.ReGoods;
import com.crm.aftersale.domain.query.ReGoodsQuery;
import com.crm.aftersale.domain.vo.ReGoodsVo;
import com.crm.aftersale.mapper.GoodsMapper;
import com.crm.aftersale.mapper.OrderGoodsMapper;
import com.crm.aftersale.mapper.ReGoodsMapper;
import com.crm.aftersale.service.IReGoodsService;
import com.crm.base.domain.AjaxResult;
import com.crm.base.domain.User;
import com.crm.base.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ReGoodsServiceImpl extends ServiceImpl<ReGoodsMapper, ReGoods> implements IReGoodsService {

    @Autowired
    private ReGoodsMapper reGoodsMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public AjaxResult findReGoods(@RequestBody ReGoodsQuery reGoodsQuery) {

        if (Objects.isNull(reGoodsQuery)) {
            reGoodsQuery = new ReGoodsQuery();
        }
        System.out.println(reGoodsQuery);
        Page<ReGoods> page = new Page<>(reGoodsQuery.getCurrent(), reGoodsQuery.getSize());

        Page<ReGoods> reGoodsPage = reGoodsMapper.selectPage(page, Wrappers.<ReGoods>lambdaQuery()
                .like(Objects.nonNull(reGoodsQuery.getOrderNum()), ReGoods::getOrderNum, reGoodsQuery.getOrderNum())
                .like(StringUtils.hasText(reGoodsQuery.getRecorder()), ReGoods::getRecorder, reGoodsQuery.getRecorder())
                .like(StringUtils.hasText(reGoodsQuery.getApprover()), ReGoods::getApprover, reGoodsQuery.getApprover())
                .like(StringUtils.hasText(reGoodsQuery.getTypee()), ReGoods::getTypee, reGoodsQuery.getTypee())
                .ge((reGoodsQuery.getRecordTime() != null && reGoodsQuery.getRecordTime().length > 0), ReGoods::getRecordTime, reGoodsQuery.getStartTime1())
                .le((reGoodsQuery.getRecordTime() != null && reGoodsQuery.getRecordTime().length > 0), ReGoods::getRecordTime, reGoodsQuery.getEndTime1())
                .ge((reGoodsQuery.getApproveTime() != null && reGoodsQuery.getApproveTime().length > 0), ReGoods::getApproveTime, reGoodsQuery.getStartTime2())
                .le((reGoodsQuery.getApproveTime() != null && reGoodsQuery.getApproveTime().length > 0), ReGoods::getApproveTime, reGoodsQuery.getEndTime2()));

        ReGoodsVo reGoodsVo = new ReGoodsVo();

        reGoodsVo.setReGoods(reGoodsPage.getRecords());
        reGoodsVo.setTotal(reGoodsPage.getTotal());
        reGoodsVo.setCurrent(reGoodsPage.getCurrent());


        return AjaxResult.me().setData(reGoodsVo);
    }

    @Override
    public ReGoodsVo findByOrderId(Integer orderId) {

        ReGoodsVo reGoodsVo = reGoodsMapper.selectAllByOrderId(orderId);
        System.out.println(reGoodsVo);
        return reGoodsVo;
    }

    @Override
    public Integer addReGoods(ReGoods reGoods, HttpServletRequest req) {

        String token = req.getHeader("X-Token");
        if (StringUtils.hasText(token)) {
            User user = JWTUtils.parse(token);
            reGoods.setRecorder(user.getUserName());
        }
        reGoods.setTypee("0");
        reGoods.setRecordTime(LocalDate.now());


        int insert = 0;
        try {
            insert = reGoodsMapper.insert(reGoods);
            return insert;
        } catch (Exception e) {
            return 0;
        }

    }

    @Override
    public Integer updateReGoods(ReGoods reGoods, HttpServletRequest req) {
        String token = req.getHeader("X-Token");
        if (StringUtils.hasText(token)) {
            User user = JWTUtils.parse(token);
            reGoods.setRecorder(user.getUserName());
        }
        reGoods.setTypee("0");
        reGoods.setRecordTime(LocalDate.now());


        int update = 0;
        try {
            update = reGoodsMapper.updateById(reGoods);
            return update;
        } catch (Exception e) {
            return 0;
        }
    }
    @Override
    public Integer updateType(ReGoods reGoods, HttpServletRequest req) {
        String token = req.getHeader("X-Token");
        if (StringUtils.hasText(token)) {
            User user = JWTUtils.parse(token);
            reGoods.setApprover(user.getUserName());
        }
        reGoods.setApproveTime(LocalDate.now());


        int update = 0;
        try {
            update = reGoodsMapper.updateById(reGoods);
            return update;
        } catch (Exception e) {
            return 0;
        }
    }
    @Override
    public Integer deleteReGoods(ReGoods reGoods) {
        int delete = 0;
        try {
            delete = reGoodsMapper.deleteById(reGoods);
            return delete;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public AjaxResult fileDown(HttpServletResponse response) {
        try {
            List<ReGoods> reGoods = reGoodsMapper.selectList(Wrappers.<ReGoods>lambdaQuery());
            ArrayList<ReGoods> rows = CollUtil.newArrayList(reGoods);
            // 通过工具类创建writer，默认创建xls格式
            ExcelWriter writer = ExcelUtil.getWriter("d:/writeBeanTest.xlsx");

            //自定义标题别名
            writer.merge(16, "退货申请表");
            writer.addHeaderAlias("orderNum", "单据编号");
            writer.addHeaderAlias("recorder", "制单人");
            writer.addHeaderAlias("recordTime", "制单时间");
            writer.addHeaderAlias("recordName", "申诉记录名称");
            writer.addHeaderAlias("recordDecss", "申诉记录描述");
            writer.addHeaderAlias("approver", "审批人");
            writer.addHeaderAlias("approveTime", "审批时间");
            writer.addHeaderAlias("serviceOne", "客服答复意见");
            writer.addHeaderAlias("serviceOneTime", "客服答复日期");
            writer.addHeaderAlias("serviceTwo", "二次客服答复意见");
            writer.addHeaderAlias("serviceTwoTime", "二次客服答复日期");

            writer.setOnlyAlias(true);//只显示起别名的
// 一次性写出内容，使用默认样式，强制输出标题
            writer.write(rows, true);

// 关闭writer，释放内存
            writer.close();

            return AjaxResult.me("导出成功");
        } catch (Exception e) {
            return AjaxResult.me("导出失败");
        }

    }

}
